package com.aaa.bookproject.controller;


import com.aaa.bookproject.entity.TLogin;
import com.aaa.bookproject.service.ITLoginService;
import com.aaa.bookproject.util.ResultData;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Set;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author LvYongQi
 * @since 2021-05-09
 */
@RestController
@RequestMapping("/t-login")
public class TLoginController {

    @Resource
    private ResultData resultData;
    @Resource
    private ITLoginService loginService;

    @PostMapping("login")
    public ResultData login(TLogin tLogin){
        System.out.println(tLogin+"===========");
        // 获取当前操作的主体
        Subject subject = SecurityUtils.getSubject();
        // 将用户的账号与密码存token中
        UsernamePasswordToken usernamePasswordToken =
                new UsernamePasswordToken(tLogin.getLoginid(),tLogin.getLoginpsw());
        // 使用UserRealm中的方法进行验证
        try {
            subject.login(usernamePasswordToken);
        } catch (AuthenticationException e) {
            // 登录失败
            resultData.setMsg("用户名或密码不正确");
            resultData.setCode(400);
            return resultData;
        }
        // 登录成功
        TLogin login = (TLogin) subject.getPrincipal();
        if (login != null) {
            // 查询该用户的角色信息
            Set<String> roles = loginService.getRoleidByStaffid(login.getStaffid());
            // 将角色信息存入
            login.setRoles(roles);
            // 查询该用户所具有的资源文件
            Set<String> menus = loginService.getMenusByStaffid(login.getStaffid());
            login.setMenus(menus);
            resultData.setData(login);
            resultData.setMsg("登录成功！！！！");
            resultData.setCode(200);
        }
        return resultData;
    }
}

